package portlet;

import java.io.IOException;

import java.util.Locale;

import java.util.ResourceBundle;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import javax.portlet.PortletRequest;

import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.model.binding.DCIteratorBinding;

import oracle.binding.BindingContainer;

import oracle.jbo.ViewObject;
import oracle.jbo.uicli.binding.JUCtrlRangeBinding;

public class Utils {
    public Utils() {
        super();
    }

    public static Locale getPortalLocale() {
        Locale portalLocale = new Locale("vi", "VN");
        try {
            portalLocale =
                    new Locale(getPortletRequest().getParameter("lang"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return portalLocale;
    }

    public static String getResource(String resourceKey) {
        Locale locale = getPortalLocale();
        ResourceBundle bundle =
            ResourceBundle.getBundle("portlet.resource.PortletsBundle",
                                     locale);
        return bundle.getString(resourceKey);
    }

    public static PortletRequest getPortletRequest() {
        PortletRequest req =
            (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        return req;
    }

    public static void redirect(String url) {
        ExternalContext externalContext =
            FacesContext.getCurrentInstance().getExternalContext();
        try {
            externalContext.redirect(url);
        } catch (IOException e) {
        }
    }

    public static String goLastPage(Integer RANGE_SIZE,
                                    String viewObjectName) {
        JUCtrlRangeBinding OV = getViewObject(viewObjectName);
        long lastPageNum =
            Math.max(1, (OV.getIteratorBinding().getEstimatedRowCount() - 1) /
                     RANGE_SIZE + 1);
        if (lastPageNum <= 1)
            return null;
        int prePage =
            OV.getIteratorBinding().getNavigatableRowIterator().getRangeStart() /
            RANGE_SIZE + 1;
        OV.getIteratorBinding().getNavigatableRowIterator().scrollRange((int)(RANGE_SIZE *
                                                                              (lastPageNum -
                                                                               prePage)));
        OV.setCurrentRowAtIndex(0);
        return null;
    }

    public static boolean isLastEnabled(Integer RANGE_SIZE,
                                        String viewObjectName) {
        JUCtrlRangeBinding OV = getViewObject(viewObjectName);
        long lastPageNum =
            Math.max(1, (OV.getIteratorBinding().getEstimatedRowCount() - 1) /
                     RANGE_SIZE + 1);
        long currentPage =
            OV.getIteratorBinding().getNavigatableRowIterator().getRangeStart() /
            RANGE_SIZE + 1;
        return currentPage < lastPageNum;
    }

    public static boolean isFirstEnabled(Integer RANGE_SIZE,
                                         String viewObjectName) {
        boolean isFirst = true;
        JUCtrlRangeBinding OV = getViewObject(viewObjectName);
        if (OV != null) {
            long currentPage =
                OV.getIteratorBinding().getNavigatableRowIterator().getRangeStart() /
                RANGE_SIZE + 1;
            if (currentPage == 1) {
                isFirst = false;
            }
        }
        return isFirst;
    }

    public static JUCtrlRangeBinding getViewObject(String viewObjectName) {
        BindingContext bindingCtx = BindingContext.getCurrent();
        BindingContainer bindings = bindingCtx.getCurrentBindingsEntry();
        return (JUCtrlRangeBinding)bindings.getControlBinding(viewObjectName);
    }

    public static DCIteratorBinding getIteratorBinding(String iteratorName) {
        return getDCBindingContainer().findIteratorBinding(iteratorName);
    }

    public static DCBindingContainer getDCBindingContainer() {
        return (DCBindingContainer)getBindingContainer();
    }

    public static BindingContainer getBindingContainer() {
        return (BindingContainer)getElExpression("#{bindings}");
    }

    /**
     * @param el
     * @return
     */
    public static Object getElExpression(String el) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ELContext elContext = facesContext.getELContext();
        ExpressionFactory expressionFactory =
            facesContext.getApplication().getExpressionFactory();
        ValueExpression valueExp =
            expressionFactory.createValueExpression(elContext, el,
                                                    Object.class);
        return valueExp.getValue(elContext);
    }

    /**
     * @param el
     * @param val
     */
    public static void setElExpression(String el, Object val) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ELContext elContext = facesContext.getELContext();
        ExpressionFactory expressionFactory =
            facesContext.getApplication().getExpressionFactory();
        ValueExpression exp =
            expressionFactory.createValueExpression(elContext, el,
                                                    Object.class);
        exp.setValue(elContext, val);
    }

    /**
     * Refresh a View Iterator
     * @param iteratorName
     */
    public static void iteratorRefresh(String iteratorName) {
        try {
            DCBindingContainer dcBinding =
                (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
            DCIteratorBinding ViewIterator =
                (DCIteratorBinding)dcBinding.get(iteratorName);
            ViewIterator.getViewObject().clearCache();
            int oldMode = ViewIterator.getViewObject().getQueryMode();
            ViewIterator.getViewObject().setQueryMode(ViewObject.QUERY_MODE_SCAN_DATABASE_TABLES);
            ViewIterator.executeQuery();
            ViewIterator.getViewObject().setQueryMode(oldMode);
            ViewIterator.refresh(DCIteratorBinding.RANGESIZE_UNLIMITED);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
